<script lang="ts" setup>
import { getProjectUsingGet } from '@/api/projectController'
import { addRequirementUsingPost } from '@/api/requirementController'
import { FormInstance, Message } from '@arco-design/web-vue'
import { IDomEditor } from '@wangeditor/editor'
import dayjs from 'dayjs'
import { computed, onMounted, Ref, ref, shallowRef } from 'vue'
import { PRIORITY_CONFIG, getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import { editorConfig, editorStyle } from '@/composables/useEditorConfig'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { addIterationUsingPost } from '@/api/iterationController'
defineOptions({
  name: 'IterationCreate'
})
const props = defineProps<{
  visible: boolean
  proId: number
}>()
const iterationModalVisible = ref(false)
const emit = defineEmits(['reload', 'close', 'update:visible'])
// 迭代表单数据
const addIterationRequest: Ref<API.AddIterationRequest> = ref({
  title: '',
  description: '',
  remark: '',
  priority: 0,
  mileId: undefined as number | undefined,
  proId: undefined as number | undefined,
  startTime: '',
  endTime: ''
})
// 表单实例
const iterationFormRef = ref<FormInstance | null>(null)
// 迭代表单规则
const iterationRules = {
  title: [
    { required: true, message: '请输入迭代标题' },
    { maxLength: 50, message: '标题最多50个字符' }
  ],
  startTime: [{ required: true, message: '请选择开始时间' }],
  endTime: [{ required: true, message: '请选择结束时间' }],
  mileId: [{ required: true, message: '请选择里程碑' }]
}
const handleSubmitIteration = async () => {
  addIterationRequest.value.proId = props.proId
  // 校验时间
  if (
    dayjs(addIterationRequest.value.startTime).isAfter(dayjs(addIterationRequest.value.endTime))
  ) {
    Message.error('开始时间不能晚于结束时间')
    return false
  }
  // 格式化时间
  addIterationRequest.value.startTime = dayjs(addIterationRequest.value.startTime).format(
    'YYYY-MM-DDTHH:mm:ss'
  )
  addIterationRequest.value.endTime = dayjs(addIterationRequest.value.endTime).format(
    'YYYY-MM-DDTHH:mm:ss'
  )
  const errors = await iterationFormRef.value?.validate()
  if (errors) {
    Message.error('请填写完整信息')
    return false
  }
  try {
    const res: any = await addIterationUsingPost(addIterationRequest.value)
    if (res.code === 0) {
      Message.success('添加迭代成功')
      iterationModalVisible.value = false
      // 重置表单数据
      addIterationRequest.value = {
        title: '',
        startTime: '',
        endTime: '',
        description: '',
        remark: '',
        proId: props.proId as number | undefined,
        mileId: undefined
      }
      emit('reload', true)
      return true
    } else {
      Message.error(res.message || '添加迭代失败')
      iterationModalVisible.value = false
      return false
    }
  } catch (error) {
    console.error('添加迭代失败:', error)
    iterationModalVisible.value = false
    return false
  }
}
const iterationDescriptionEditor = shallowRef()
const iterationRemarkEditor = shallowRef()
// 在弹窗关闭时也清理编辑器实例
const handleRequirementModalClose = () => {
  if (iterationDescriptionEditor.value) {
    iterationDescriptionEditor.value.destroy()
    iterationDescriptionEditor.value = null
  }
  if (iterationRemarkEditor.value) {
    iterationRemarkEditor.value.destroy()
    iterationRemarkEditor.value = null
  }
  emit('close')
}
// 获取项目成员
const projectMembers = ref<API.UserInProjectVo[]>([])
// 当前选中项
const currentMilestone = ref()
// 切换里程碑，时间范围重新获取
const handleMilestoneChange = (val: any) => {
  currentMilestone.value = milestones.value?.find((milestone) => milestone.id == val)

  // 当切换里程碑时，重置迭代的开始和结束时间
  if (currentMilestone.value) {
    addIterationRequest.value.startTime = currentMilestone.value.startTime
    addIterationRequest.value.endTime = currentMilestone.value.endTime
  } else {
    // 如果取消选择里程碑，使用项目的时间范围
    addIterationRequest.value.startTime = currentProject.value?.startTime || ''
    addIterationRequest.value.endTime = currentProject.value?.endTime || ''
  }
}
// 获取项目信息
const currentProject = ref<API.ProjectVo>()
const milestones = ref<API.MileStoneVo[]>([])
const getCurrentProject = async () => {
  try {
    const res: any = await getProjectUsingGet({
      id: props.proId
    })
    if (res.code === 0) {
      currentProject.value = res.data
      milestones.value = currentProject.value?.mileStoneVoList || []
      projectMembers.value = currentProject.value?.members || []
    } else {
      Message.error(res.msg || '获取项目信息失败')
    }
  } catch (error) {
    console.error('获取项目信息失败:', error)
    Message.error('获取项目信息失败')
  }
}
const milestoneOptions = computed(() =>
  milestones.value.map((milestone) => ({
    label: milestone.title,
    value: milestone.id
  }))
)

const initStartDate = ref(currentProject.value?.startTime || '')
const initEndDate = ref(currentProject.value?.endTime || '')
const formatDateTime = (time: string | Date | null) => {
  if (!time) return null
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}
// 通用的时间变更处理函数
const handleTimeChange = (
  type: 'start' | 'end',
  value: string | null,
  options: {
    request: any // 请求对象
    parentStartTime?: string // 父级开始时间
    parentEndTime?: string // 父级结束时间
    itemType: 'milestone' | 'iteration' | 'task' // 项目类型
    parentType?: 'project' | 'milestone' // 父级类型
  }
) => {
  const formattedValue = formatDateTime(value)
  const { request, parentStartTime, parentEndTime, itemType, parentType } = options

  if (!value) {
    Message.warning(`请选择${type === 'start' ? '开始' : '结束'}时间`)
    return false
  }

  // 检查开始时间
  if (type === 'start') {
    // 检查是否在父级时间范围内
    if (parentStartTime && dayjs(value).isBefore(dayjs(parentStartTime))) {
      Message.warning(`${itemType}开始时间不能早于${parentType}开始时间`)
      return false
    }
    if (parentEndTime && dayjs(value).isAfter(dayjs(parentEndTime))) {
      Message.warning(`${itemType}开始时间不能晚于${parentType}结束时间`)
      return false
    }
    request.startTime = formattedValue
  }
  // 检查结束时间
  else {
    // 检查是否早于开始时间
    if (dayjs(value).isBefore(dayjs(request.startTime))) {
      Message.warning('结束时间不能早于开始时间')
      return false
    }
    // 检查是否在父级时间范围内
    if (parentEndTime && dayjs(value).isAfter(dayjs(parentEndTime))) {
      Message.warning(`${itemType}结束时间不能晚于${parentType}结束时间`)
      return false
    }
    request.endTime = formattedValue
  }
  return true
}
const handleTaskTimeChange = (type: 'start' | 'end', value: string | null) => {
  return handleTimeChange(type, value, {
    request: addIterationRequest.value,
    itemType: 'iteration'
  })
}
const handleDescriptionEditorCreated = (type: 'iteration', editor: IDomEditor) => {
  switch (type) {
    case 'iteration':
      if (iterationDescriptionEditor.value) {
        iterationDescriptionEditor.value.destroy()
      }
      iterationDescriptionEditor.value = editor
      break
  }
}
const handleRemarkEditorCreated = (type: 'iteration', editor: IDomEditor) => {
  switch (type) {
    case 'iteration':
      if (iterationRemarkEditor.value) {
        iterationRemarkEditor.value.destroy()
      }
      iterationRemarkEditor.value = editor
      break
  }
}
// 添加计算属性
const disabledIterationDate = computed(() => {
  return (date: Date) => {
    const currentDate = dayjs(date)

    // 如果选择了里程碑，使用里程碑的时间范围
    if (currentMilestone.value) {
      const milestoneStart = dayjs(currentMilestone.value.startTime).startOf('day')
      const milestoneEnd = dayjs(currentMilestone.value.endTime).startOf('day')
      return currentDate.isBefore(milestoneStart) || currentDate.isAfter(milestoneEnd)
    }

    // 如果没有选择里程碑，使用项目的时间范围
    if (currentProject.value) {
      const projectStart = dayjs(currentProject.value.startTime).startOf('day')
      const projectEnd = dayjs(currentProject.value.endTime).startOf('day')
      return currentDate.isBefore(projectStart) || currentDate.isAfter(projectEnd)
    }

    // 如果既没有里程碑也没有项目信息，禁用所有日期
    return true
  }
})
onMounted(async () => {
  iterationModalVisible.value = props.visible
  await getCurrentProject()
})
</script>
<template>
  <!-- 3. 迭代创建/编辑弹窗 -->
  <a-modal
    v-model:visible="iterationModalVisible"
    title="添加迭代"
    @update:visible="(val) => emit('update:visible', val)"
    @cancel="handleRequirementModalClose"
    @before-ok="handleSubmitIteration"
    modal-class="iteration-modal"
    width="auto"
    v-if="iterationModalVisible"
    :draggable="true"
  >
    <a-form
      ref="iterationFormRef"
      :model="addIterationRequest"
      :rules="iterationRules"
      layout="vertical"
      class="requirement-form"
    >
      <!-- 标题 -->
      <a-form-item field="title" label="迭代标题" validate-trigger="blur">
        <a-input v-model="addIterationRequest.title" placeholder="请输入迭代标题" allow-clear />
      </a-form-item>
      <!-- 关联里程碑 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="mileId" label="关联里程碑">
            <a-select
              v-model="addIterationRequest.mileId"
              placeholder="请选择里程碑"
              @change="handleMilestoneChange"
              allow-clear
            >
              <a-option
                v-for="option in milestoneOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 时间选择 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="startTime" label="开始时间">
            <a-date-picker
              v-model="addIterationRequest.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始时间"
              style="width: 100%"
              :disabled-date="disabledIterationDate"
              :default-value="initStartDate"
              @change="(value) => handleTaskTimeChange('start', value)"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="endTime" label="结束时间">
            <a-date-picker
              v-model="addIterationRequest.endTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束时间"
              style="width: 100%"
              :disabled-date="disabledIterationDate"
              :default-value="initEndDate"
              @change="(value) => handleTaskTimeChange('end', value)"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 描述编辑器 -->
      <a-form-item field="description" label="描述">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid var(--color-border)"
            :editor="iterationDescriptionEditor"
            mode="default"
          />
          <Editor
            v-model="addIterationRequest.description"
            :default-config="editorConfig"
            :style="editorStyle"
            mode="default"
            v-if="iterationModalVisible"
            @on-created="(editor) => handleDescriptionEditorCreated('iteration', editor)"
          />
        </div>
      </a-form-item>

      <!-- 备注编辑器 -->
      <a-form-item field="remark" label="备注">
        <div class="editor-container">
          <Toolbar
            style="border-bottom: 1px solid var(--color-border)"
            :editor="iterationRemarkEditor"
            mode="default"
          />
          <Editor
            v-model="addIterationRequest.remark"
            :default-config="editorConfig"
            :style="editorStyle"
            mode="default"
            v-if="iterationModalVisible"
            @on-created="(editor) => handleRemarkEditorCreated('iteration', editor)"
          />
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style></style>
